package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.Stock;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ActionServlet extends HttpServlet {

	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("service()"); // 追踪
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		String path = req.getServletPath(); // 获取资源网名
		System.out.println(path); // 打印网名供开发者查看
		
		if("/stock.do".equals(path)) {
			stock_info(req, resp, out);
		}
		if("/random_number.do".equals(path)) {
			random_number(req, resp, out);
		}
		if("/checkName.do".equals(path)) {
			checkName(req, resp, out);
		}
	}
	
	private void stock_info(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
		System.out.println("stock_info()");
		List<Stock> stocks = new ArrayList<Stock>();
		Random r = new Random();
		Integer number = r.nextInt(100);
//		out.println(number);
		for(int i = 0; i < 5; i++) {
			Stock stock = new Stock();
			stock.setCode(110 + i);
			stock.setName("重庆力帆" + i);
			stock.setPrice(r.nextInt(20));
			stocks.add(stock);
		}
		JSONArray jsonArr = JSONArray.fromObject(stocks);
		String arr = jsonArr.toString();
		out.println(arr);
	}
	
	private void random_number(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
		System.out.println("random_number()");
		
		Random r = new Random();
		Integer number = r.nextInt(100);
		out.println(number);
		
	}
	
	private void checkName(HttpServletRequest req, HttpServletResponse resp, PrintWriter out) throws ServletException, IOException {
		System.out.println("checkName()");
		
		String name = req.getParameter("name");
		System.out.println(name);  // 打印请求参数
		String age = req.getParameter("age");
		System.out.println(age);
		System.out.println("hello");
		
		if("warrior".equals(name)) {
			out.println("该用户名已经存在，请重写输入");
		}else {
			out.println("该用户名可以使用");
		}
		
		
	}

}
